package main

import (
	"fmt"
	"server_cluster/common/config"
	"server_cluster/common/logger"
	"server_cluster/logic/db"
	"server_cluster/logic/game_config"
	"server_cluster/logic/gamelogic"
	"server_cluster/logic/sharemem"
	"strconv"
	"time"
)

func game_sync() {
	err := db.InitDB()
	if err != nil {
		panic(fmt.Sprintf("init db fail. %v", err))
	}

	logger.Info("game sync start...")
	myshm := sharemem.MyShm
	myshm.StatusSync = 1

	logger.Info("game sync loop...")

	userIndex := int32(0)
	for myshm.StatusSync == 1 {
		if userIndex >= game_config.USER_MAX {
			userIndex = 0
			time.Sleep(time.Second * 10 * 60)
		}
		if sharemem.MyShm.Usr[userIndex].Id.NewVal == 0 {
			// 索引空数据
			userIndex++
			continue
		}
		sharemem.SemWait(&(sharemem.MyShm.SemUser[userIndex]))
		if sharemem.MyShm.Usr[userIndex].Id.NewVal == 0 {
			// 索引空数据
			sharemem.SemPost(&(sharemem.MyShm.SemUser[userIndex]))
			userIndex++
			continue
		}
		res := gamelogic.MD_User(userIndex, true)
		if res != nil {
			user := &(sharemem.MyShm.Usr[userIndex])
			logger.Error("save user fail,error :%v, uid: %v", res, user.GetUid())
			sharemem.SemPost(&(sharemem.MyShm.SemUser[userIndex]))
			// 保存失败
			gamelogic.DumpPlayerData(user)
		} else {
			if sharemem.MyShm.Usr[userIndex].IsOnline == false &&
				(myshm.TimeNow-sharemem.MyShm.Usr[userIndex].LastOfflineTime) > config.USER_TIME_MAX {
				sharemem.MyShm.Usr[userIndex].ClearUserWithOutLock()
			}
			sharemem.SemPost(&(sharemem.MyShm.SemUser[userIndex]))
		}
		userIndex++
		time.Sleep(time.Second * 1)
	}
	myshm.StatusSync = 0
	logger.Info("game sync stop.")
}

func main() {
	game_config.InitConfig()
	logger.InitLogger("sync_"+strconv.Itoa(int(game_config.GetConfig().ServerId)), game_config.GetConfig().LogLevel)
	defer logger.CloseLogger()
	shmid := sharemem.GetShm()
	if shmid <= 0 {
		logger.Error("Get myshm fail.")
		return
	}
	myshm := sharemem.MyShm
	if myshm.StatusSync != 0 {
		logger.Error("Server sync is not init. StatusSync:%v", myshm.StatusSync)
		return
	}

	game_sync()
}
